package com.lcx.plugin.neteaseCloud.music.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lcx.plugin.neteaseCloud.music.DataCenter;
import com.lcx.plugin.neteaseCloud.util.NetWorkUtil;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import java.util.logging.Logger;

public class UserApi {

    private static final Logger log = Logger.getLogger(UserApi.class.getName());

    private static String key = null;
    public static String qrCodeStr = null;

    /**
     * 通过手机号登录
     * 请在登录前手动设置密码及手机号
     *
     * @return 状态码
     */
    public static int loginByPhoneNumber(String phoneNumber, String password) {
        if (password == null || phoneNumber == null) {
            return 401;
        }
        password = setPassword(password, false);
        String result = NetWorkUtil.sendByGetUrl(String.format("/login/cellphone?phone=%s&md5_password=%s", phoneNumber, password), null);
        if (result == null) {
            return -1;
        }
        DataCenter.userInfo = JSON.parseObject(result);
        System.out.println(DataCenter.userInfo);
        DataCenter.userProfile = getProfile();
        return DataCenter.userInfo.getInteger("code");
    }

    /**
     * 通过验证码登录
     * 请在登录前手动设置验证码及手机号
     *
     * @return 状态码
     */
    public static int loginByPhoneCode(String phoneNumber, String phoneCode) {
        if (phoneCode == null || phoneNumber == null) {
            return 401;
        }
        // 先验证二维码
        String verify = NetWorkUtil.sendByGetUrl(String.format("/captcha/verify?phone=%s&captcha=%s", phoneNumber, phoneCode), null);
        if (verify == null) {
            return -1;
        }
        JSONObject verifyObj = JSON.parseObject(verify);
        Integer code = verifyObj.getInteger("code");
        if (!Objects.equals(code, 200)) {
            return -1;
        }
        String result = NetWorkUtil.sendByGetUrl(String.format("/login/cellphone?phone=%s&countrycode=86&captcha=%s", phoneNumber, phoneCode), null);
        if (result == null) {
            return -1;
        }
        DataCenter.userInfo = JSON.parseObject(result);
        System.out.println(DataCenter.userInfo);
        DataCenter.userProfile = getProfile();
        return DataCenter.userInfo.getInteger("code");
    }

    /**
     * 通过手机号登录
     * 请在登录前手动设置密码及邮箱
     *
     * @return 状态码
     */
    public static int loginByEmail(String email, String password) {
        if (password == null || email == null) {
            return 401;
        }
        password = setPassword(password, false);
        String result = NetWorkUtil.sendByGetUrl(String.format("/login?email=%s&md5_password=%s", email, password), null);
        if (result == null) {
            return -1;
        }
        DataCenter.userInfo = JSON.parseObject(result);
        System.out.println(DataCenter.userInfo);
        DataCenter.userProfile = getProfile();
        return DataCenter.userInfo.getInteger("code");
    }

    /**
     * 设置密码
     * 请在登录前执行
     *
     * @param password 密码
     * @param md5      是否已进行md5加密（若为否则自动加密）
     */
    public static String setPassword(String password, Boolean md5) {
        if (!md5) {
            return encodeByMD5(password);
        } else {
            return password;
        }
    }

    /**
     * 设置Cookie
     *
     * @param cookie cookie
     */
    public static void setCookie(String cookie) {
        DataCenter.userInfo.put("cookie", cookie);
    }

    /**
     * 申请二维码密钥
     *
     * @return 是否获取成功
     */
    public static Boolean getKey() {
        String result = NetWorkUtil.sendByGetUrl("/login/qr/key?timerstamp=" + System.currentTimeMillis(), null);
        if (result == null || JSON.parseObject(result).getJSONObject("data").getString("unikey") == null) {
            return false;
        } else {
            key = JSON.parseObject(result).getJSONObject("data").getString("unikey");
            return true;
        }
    }

    /**
     * 创建二维码
     *
     * @return base64二维码
     */
    public static String createQRCode() {
        String result = NetWorkUtil.sendByGetUrl(String.format("/login/qr/create?key=%s&qrimg=1&timerstamp=" + System.currentTimeMillis(), key), null);
        if (result == null || JSON.parseObject(result).getJSONObject("data").getString("qrimg") == null) {
            return null;
        } else {
            qrCodeStr = JSON.parseObject(result).getJSONObject("data").getString("qrimg");
            return qrCodeStr;
        }
    }

    /**
     * 检查二维码状态
     *
     * @return 状态码
     */
    public static int checkQRStatus() {
        String result = NetWorkUtil.sendByGetUrl(String.format("/login/qr/check?key=%s&timerstamp=" + System.currentTimeMillis(), key), "");
        if (result == null) {
            return -1;
        } else {
            JSONObject tmp = JSON.parseObject(result);
            int code = JSON.parseObject(result).getInteger("code");
            if (code == 803) {
                log.info("二维码登录成功，返回结果为：" + tmp);
                DataCenter.userInfo.put("cookie", tmp.getString("cookie"));
                DataCenter.cookie = tmp.getString("cookie");
            }
            return code;
        }
    }

    /**
     * 获取Cookie
     * 请先登录
     *
     * @return cookie
     */
    public static String getCookie() {
        return DataCenter.userInfo.getString("cookie");
    }

    /**
     * 获取用户信息
     * 请先登录
     *
     * @return 用户信息
     */
    public static JSONObject getProfile() {
        if (DataCenter.userInfo.getString("profile") == null) {
            return JSON.parseObject(NetWorkUtil.sendByGetUrl("/login/status?timerstamp=" + System.currentTimeMillis(), getCookie()))
                    .getJSONObject("data").getJSONObject("profile");
        }
        return DataCenter.userInfo.getJSONObject("profile");
    }

    public static JSONObject checkLogin() {
        return JSON.parseObject(NetWorkUtil.sendByGetUrl("/login/status", getCookie())).getJSONObject("data");
    }

    public static void logout() {
        NetWorkUtil.sendByGetUrl("/logout", getCookie());
    }

    /**
     * md5加密
     *
     * @param str 待加密字符串
     */
    public static String encodeByMD5(String str) {
        byte[] secretBytes;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    str.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("md5 error");
        }
        StringBuilder md5code = new StringBuilder(new BigInteger(1, secretBytes).toString(16));
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code.insert(0, "0");
        }
        return md5code.toString();
    }

    /**
     * 发送验证码
     *
     * @param phoneNumber
     * @return java.lang.String
     * @author daxiong
     * @date 2021/10/10 上午10:54
     */
    public static int sendPhoneCode(String phoneNumber) {
        String result = NetWorkUtil.sendByGetUrl(String.format("/captcha/sent?phone=%s", phoneNumber), null);
        if (result == null) {
            return -1;
        } else {
            JSONObject tmp = JSON.parseObject(result);
            return tmp.getInteger("code");
        }
    }

}
